package com.example.wan1.view.homenew;

import android.app.Activity;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.wan1.R;
import com.example.wan1.adapter.BannerImageAdapter;
import com.example.wan1.adapter.MixedHomeAdapter;
import com.example.wan1.base.fragment.SimpleFragment;
import com.example.wan1.constant.Constants;
import com.example.wan1.model.ArticleBean;
import com.example.wan1.model.BannerBean;
import com.example.wan1.model.MixedEntity;
import com.example.wan1.model.MixedHomeEntity;
import com.example.wan1.model.common.CommonResList;
import com.example.wan1.utils.ToolsUtils;
import com.example.wan1.view.collect.HandleCollectTool;
import com.example.wan1.view.login.UserManager;
import com.example.wan1.view.web.JumpTool;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/***
 * @Author: zxd
 * @CreateDate: 2021/5/13 14:04
 * @Description:
 */
public class NewHomeFragment extends SimpleFragment implements NewHomeContract.View,
        OnLoadMoreListener, OnRefreshListener {

    @BindView(R.id.home_rv)
    RecyclerView mHomeRv;
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;

    @Inject
    NewHomePresenter mPresenter;
    @Inject
    List<MixedHomeEntity> mData;
    @Inject
    MixedHomeAdapter mAdapter;
//    @BindView(R.id.banner)
//    Banner mBanner;
//    @BindView(R.id.s_appbar)
//    AppBarLayout mAppBarLayout;

    //    @BindView(R.id.gs_scroll)
//    GradationScrollView mScrollView;
//    @BindView(R.id.toolbar1)
//    Toolbar mToolbar1;
    @BindView(R.id.newhome_rl)
    RelativeLayout mNewhomeRl;
    @BindView(R.id.ll_title_container)
    LinearLayout mLlTitleContainer;
    @BindView(R.id.newhome_title)
    TextView mNewhomeTitle;
    @BindView(R.id.newhome_search)
    ImageView mNewhomeSearch;

    private int page = 0;
    private List<BannerBean> mBannerList;//轮播图的数据
    private Banner mBanner;
    private ColorDrawable mTitleBackground;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBannerList = new ArrayList<>();
    }

    @Override
    protected void initData() {
        showLoading();
        mPresenter.getBannerList();
        mPresenter.start();
    }

    @Override
    protected void initView() {
        mHomeRv.setAdapter(mAdapter);
        //禁止垂直滑动
        /*LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };*/
        //getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        mHomeRv.setLayoutManager(new LinearLayoutManager(mContext));
        mHomeRv.setHasFixedSize(true);
        mHomeRv.setNestedScrollingEnabled(false);

        mSrl.setOnLoadMoreListener(this);
        mSrl.setOnRefreshListener(this);

        mSrl.setEnableRefresh(false);
        mSrl.setEnableLoadMore(false);

        mAdapter.setOnItemClickListener((baseQuickAdapter, view1, i) -> {
            JumpTool.goWeb(mContext, mData.get(i).getBean().getTitle(), mData.get(i).getBean().getLink());
            HandleCollectTool.getInstance().setInfo(mData.get(i).getBean(), i, Constants.PROJECT);
        });

        mAdapter.setOnItemChildClickListener((baseQuickAdapter, view, i) -> {
            switch (view.getId()) {
                case R.id.project_list_collect: {
                    if (!UserManager.getInstance().isLogin()) {
                        JumpTool.goLogin(getActivity());
                        return;
                    }
                    ArticleBean articleBean = mData.get(i).getBean();
                    HandleCollectTool.getInstance().setInfo(articleBean, i, Constants.PROJECT);
                    ImageView iv = view.findViewById(R.id.project_list_collect);
                    if (articleBean.isCollect()) {
                        HandleCollectTool.getInstance().cancelList();
                        iv.setImageResource(R.mipmap.heart_gray);
                    } else {
                        HandleCollectTool.getInstance().collectIn();
                        iv.setImageResource(R.mipmap.heart_red);
                    }
                }
                break;
            }
        });

        mHomeRv.addOnScrollListener(mOnScrollListener);

        mBanner = (Banner) LayoutInflater.from(mContext).inflate(R.layout.home_banner_newhome, mNewhomeRl, false);
        mBanner.setAdapter(new BannerImageAdapter(mBannerList))
                .addBannerLifecycleObserver(this)//添加生命周期观察者
                .setIndicator(new CircleIndicator(mContext));
        mAdapter.addHeaderView(mBanner);

        mBanner.setFocusable(true);
        mBanner.setFocusableInTouchMode(true);
        mBanner.requestFocus();

        //setImgTransparent(getActivity());
        /*ViewTreeObserver vto = mBanner.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mToolbar1.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                height = mBanner.getHeight();
                mScrollView.setScrollViewListener(new GradationScrollView.ScrollViewListener() {
                    @Override
                    public void onScrollChanged(GradationScrollView scrollView, int x, int y, int oldx, int oldy) {
                        if (y <= 0) {   //设置标题的背景颜色
                            mToolbar1.setBackgroundColor(Color.argb((int) 0, 144, 151, 166));
                        } else if (y > 0 && y <= height) { //滑动距离小于图片的高度时，设置背景和字体颜色颜色透明度渐变
                            float scale = (float) y / height;
                            float alpha = (255 * scale);
                            //toolbar_title.setTextColor(Color.argb((int) alpha, 255, 255, 255));
                            mToolbar1.setBackgroundColor(Color.argb((int) alpha, 144, 151, 166));
                        } else {    //滑动到下面设置普通颜色
                            mToolbar1.setBackgroundColor(Color.argb((int) 255, 144, 151, 166));
                        }
                    }
                });
            }
        });*/

        distance = ToolsUtils.dp2px(100);
        mHomeRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                /**
                 * 颜色渐变的计算
                 */
                sum += dy;
                if (sum > distance) {
                    alpha = 255;  //255表示不透明
                    mNewhomeTitle.setVisibility(View.VISIBLE);
                    mNewhomeTitle.setTextColor(Color.WHITE);
                    mNewhomeSearch.setImageTintList(ColorStateList.valueOf(Color.WHITE));
                } else if (sum <= 50) {
                    mNewhomeTitle.setVisibility(View.GONE);
                    mNewhomeTitle.setTextColor(Color.BLACK);
                    mNewhomeSearch.setImageTintList(ColorStateList.valueOf(Color.BLACK));
                    alpha = 0;
                } else { //按比例增加不透明度
                    alpha = sum * 200 / distance;
                    alpha += 55;
                    mNewhomeTitle.setVisibility(View.GONE);
                    mNewhomeTitle.setTextColor(Color.BLACK);
                    mNewhomeSearch.setImageTintList(ColorStateList.valueOf(Color.BLACK));
                }
                Log.e("home", "alpha:$alpha" + "  sum:$sum");
                //mToolbar1.setBackgroundColor(Color.argb(alpha, 0x2B, 0x6C, 0xEC));
                //mLlTitleContainer.setBackgroundColor(Color.argb(alpha, 0x2B, 0x6C, 0xEC));
                //mLlTitleContainer.setBackgroundColor(Color.argb(alpha, 16, 213, 186));
                if (mTitleBackground == null)
                    mTitleBackground = (ColorDrawable) mLlTitleContainer.getBackground();
                mTitleBackground.setAlpha(alpha);
                mLlTitleContainer.setBackground(mTitleBackground);
            }
        });

        mNewhomeSearch.setOnClickListener(v -> JumpTool.goSearch(mContext, Constants.SEARCH_NORMAL_TYPE));

        //处理颜色主题的banner选择的小点颜色
        if (ToolsUtils.getThemeColor(getActivity()) != 0) {
            mBanner.setIndicatorSelectedColor(ToolsUtils.getColor(getActivity()));
            mLlTitleContainer.setBackgroundColor(ToolsUtils.getColor(getActivity()));
        }
    }

    private int sum = 0;
    private int distance = 0;
    private int alpha = 0;

    //版本判断

    public void setImgTransparent(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }
    }

    @Override
    protected int initLayoutRes() {
        return R.layout.fragment_newhome;
    }

    @Override
    public void onSuccess(CommonResList<ArticleBean> data) {
        //没用
    }

    @Override
    public void onSuccessBanner(List<BannerBean> data) {
        Log.i("zxd", "onSuccessBanner: " + data.size());
        mBannerList.clear();
        mBannerList.addAll(data);
        mBanner.setDatas(mBannerList);
    }

    @Override
    public void onFailure(String msg) {
        showError();
    }

    @Override
    public void onSuccessArticle(List<ArticleBean> data) {
        hideLoading();
        if (data.size() > 0) {
            mSrl.setEnableRefresh(true);
            mSrl.setEnableLoadMore(true);
        }

        Collections.sort(data, (o1, o2) -> {
            if (o1.getPublishTime() > o2.getPublishTime()) {
                return -1;
            }
            return 1;
        });
        for (int i = data.size() - 1; i > 1; i--) {
            if (data.get(i).getTitle().equals(data.get(i - 1).getTitle()))
                data.remove(i);
        }
        for (int i = 0; i < data.size(); i++) {
            MixedHomeEntity item;
            if (TextUtils.isEmpty(data.get(i).getEnvelopePic()))
                item = new MixedHomeEntity(MixedEntity.ART, data.get(i));
            else
                item = new MixedHomeEntity(MixedEntity.PRO, data.get(i));
            mData.add(item);
        }
        mAdapter.notifyDataSetChanged();
        page++;
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mHomeRv.postDelayed(() -> {
            mPresenter.getArticleList(page);
            mSrl.finishLoadMore(true);
        }, 200);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mData.clear();
        mHomeRv.postDelayed(() -> {
            mPresenter.start();
            mSrl.finishRefresh(true);
        }, 200);
    }
}
